<?php 
if( defined('DOM_LOG_DIR_PATH') === false )
	die('<strong>DomFileLogger ERROR</strong>: Constant DOM_LOG_DIR_PATH is not defined!');
	
/**
* Needed constants
* DOM_LOG_DIR_PATH
*
* @author Oliver Leisalu, Inditel Meedia OÜ
* @package DomLogger
*/
class DomFileLogger {
	
	protected $name;
	protected $prefix = 'log_';
	
	public function __construct( $name ) {
		if( !preg_match('/^[A-Za-z0-9_().\'-]+$/', $name) ) {
			throw new RuntimeException('Invalid log name "'.$name.'", log name must match ^[A-Za-z0-9_().\'-]+$');
		}
		$this->name = $name;
		
	}
	
	public function getFileName() {
		return $this->prefix.$this->name.'.txt';
	}
	
	public function getFilePath() {
		return DOM_LOG_DIR_PATH . $this->getFileName();
	}
	
	/**
	* Flushes log file. It does not delete log file, it copies it to same directory as log_NAME_DATE_flush.txt.
	* @return String backup file name
	*/
	public function flush() {
		if( file_exists($this->getFilePath()) ) {
			$flushName = DOM_LOG_DIR_PATH.$this->prefix.$this->name.'_flush_'.date('Y-m-d H-i-s').'_'.mt_rand(100,999).'.txt';
			rename( $this->getFilePath(), $flushName );
		}
		return $flushName;
	}
	
	/**
	* @TODO currently not very fast as it reads full log into memory and then parses it.
	*/
	public function read( $entries = 10 ) {
		if( file_exists($this->getFilePath()) === false) return array();
		
		$result = array();
		$log = file($this->getFilePath());
		$lines = count($log);
		for( $i=$lines; $i>$lines-$entries; $i--) {
			if( $log[$i] ) 
				$result[] = $log[$i];
		}
		return $result;
		
	}
	
	/**
	* @param String $message
	*/
	public function log( $title, $message = '', $code = 0 ) {
		$h = fopen( $this->getFilePath(), 'ab');
		$message = str_replace("\n\r", "", $message );
		$message = str_replace("\n", "", $message );
		$message = str_replace("\r", "", $message );
		$message = str_replace("\t", "", $message );
		
		if( !$h )  {
			trigger_error( 'DomFileLogger can\'t write to log file. Log file is not writable or doesn\'t exist! Log file: '.$this->getFilePath(), E_USER_ERROR  );
			return false;
		}
		fwrite( $h, date('Y-m-d H:i:s').'|'.ip().'|'.(int)$code.'|'.$title.'|'.$message."\n" );
		fclose($h);
		
		return true;
	}
}
?>